#include "Rect.h"

bool Rect::intersect(const Ray &ray, IntersectResult &result) const {
	Double a0 = ray.dir * normal;
	if (a0 >= 0) return false;
	Double distance = -normal * (ray.origin - position) / a0;
	Vector3 p = ray.getPoint(distance);
	Vector3 d = position - p;

	double ddota = d * a;
	if (ddota < 0.0 || ddota > aLengthSqr) return false;

	double ddotb = d * b;
	if (ddotb < 0.0 || ddotb > bLengthSqr) return false;

	result.primitive = this;
	result.distance = distance;
	result.position = p;
	result.normal = normal;
	return true;
}

bool Rect::intersectP(const Ray & ray) const {
	Double a0 = ray.dir * normal;
	if (a0 >= 0) return false;
	Double distance = -normal * (ray.origin - position) / a0;
	Vector3 p = ray.getPoint(distance);
	Vector3 d = position - p;

	double ddota = d * a;
	if (ddota < 0.0 || ddota > aLengthSqr) return false;

	double ddotb = d * b;
	if (ddotb < 0.0 || ddotb > bLengthSqr) return false;

	return true;
}

string Rect::str() const {
	std::ostringstream s;
	s << getName() << "(pos = " << position.str() << ", normal = " << normal.str() << ")";
	return s.str();
}